<template>
  <div class="ApplicationForm">
    <div class="ApplicationForm-search">
      <span class="ApplicationForm-search-span-ls">|</span>
      <span class="ApplicationForm-search-span">危害因素</span>
    </div>
    <div class="ApplicationFormTableOne">
      <!-- :request-api="getTableList" -->
      <ProTable
        :publicsb="ApplicationFormTableOne"
        :row-key="row => row.WeiHaiYinSuID"
        ref="proTable"
        :request-auto="false"
        :columns="columns"
        :data="Tabledata"
        :yesornooperation="yesornooperation"
        :showhidden="showhidden"
        :search-col="{ xs: 1, sm: 1, md: 2, lg: 3, xl: 3 }"
        @darg-sort="dargSort"
        highlight-current-row
      >
        <!-- Expand -->
        <template #tableHeader>
          <el-button type="primary" :icon="CirclePlus" @click="addWiHaiYinSu">新增</el-button>
          <el-button type="primary" @click="saveas">另存为</el-button>
        </template>
        <template #expand="scope">
          {{ scope.row }}
        </template>
        <!-- 表格操作 -->
        <template #operation="scope">
          <el-tooltip class="box-item" effect="dark" content="编辑" placement="top">
            <el-button type="primary" link :icon="EditPen" @click="compile(scope)"></el-button>
          </el-tooltip>
          <el-tooltip class="box-item" effect="dark" content="删除" placement="top">
            <el-button type="primary" link :icon="Delete" @click="deleteWhys(scope)"></el-button>
          </el-tooltip>
        </template>
      </ProTable>
    </div>
    <el-dialog
      destroy-on-close
      @close="cancel"
      @opened="onDrawerOpened"
      v-model="centerDialogVisible"
      :title="ruleForm.strWeiHaiYinSuId != '' ? '编辑危害因素' : '添加危害因素'"
      width="40%"
      align-center
    >
      <div style="height: 40vh; overflow: scroll">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm" status-icon>
          <el-form-item label="危害因素名称" prop="strWeiHaiYinSuMingCheng">
            <el-input
              v-model="ruleForm.strWeiHaiYinSuMingCheng"
              @blur="handleBlur"
              @keydown.enter="strWeiHaiYinSuMingChengDown"
              ref="jdstrWeiHaiYinSuMingCheng"
            />
          </el-form-item>
          <el-form-item label="拼音码" prop="strPym">
            <el-input v-model="ruleForm.strPym" ref="strPymjd" />
          </el-form-item>
          <el-form-item label="类别" prop="strWeiHaiYinSuZhongLei">
            <el-select v-model="ruleForm.strWeiHaiYinSuZhongLei" style="width: 240px" disabled>
              <el-option v-for="item in kind" :key="item" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="所属院区" prop="strSuoShuYuanQu">
            <el-select
              v-model="ruleForm.strSuoShuYuanQu"
              multiple
              @change="strWeiHaiYinSuZhongLeiChange"
              collapse-tags
              collapse-tags-tooltip
              :max-collapse-tags="3"
              style="width: 240px"
            >
              <el-option v-for="item in allHospitalinquiry" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>
          <el-form-item label="国标代码" prop="strGuoBiaoDaiMa">
            <el-input v-model="ruleForm.strGuoBiaoDaiMa" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="WeiHaiYinSuCancel">取消</el-button>
          <el-button @click="WeiHaiYinSuConfirm(ruleFormRef)"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { CirclePlus, Delete, EditPen } from "@element-plus/icons-vue";
import { reactive, ref, watch, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance } from "element-plus";
import { dataWeihu } from "@/stores/datamaintenance/datatending";
import ProTable from "@/components/tablepublic/index.vue";
const centerDialogVisible = ref(false);
import {
  PostWeiHaiYinSuAddport,
  PutWeiHaiYinSuUpdateport,
  DeleteWeiHaiYinSuDeleteport,
  PostWeiHaiYinSuLingCunport,
  PutWeiHaiYinSunTiaoZhengShunXuport
} from "@/api/modules/user";
import { pinyin } from "pinyin-pro";
import { useFocusInput } from "@/utils";
import { watchEffect } from "vue";
import { nextTick } from "vue";

const ApplicationFormTableOne = ref("ApplicationFormTableOne");
const kind = ref<any>([
  { value: "粉尘", label: "粉尘" },
  { value: "生物", label: "生物" },
  { value: "物理", label: "物理" },
  { value: "毒物", label: "毒物" },
  { value: "特殊作业", label: "特殊作业" }
]);
const yesornooperation = ref("危害因素");
const Tabledata = ref<any>([]);
const allHospitalinquiry = ref<any>([]);

watchEffect(() => {
  allHospitalinquiry.value = dataWeihu().Hospitalinquiry;
});

const newShenQingDanOption = computed(() => {
  return dataWeihu().WeiHaiYinSudata;
});
const sole = ref<any>();

// 失去焦点
const handleBlur = () => {
  console.log(111);
  const firstChars = ruleForm.strWeiHaiYinSuMingCheng
    .split("")
    .map(char => pinyin(char, { style: pinyin.STYLE_NORMAL })[0])
    .join("")
    .replace(/[^a-zA-Z]/g, ""); // 使用正则表达式去除非字母字符

  const result = firstChars.toUpperCase(); // 转换为大写
  ruleForm.strPym = result;
};

const cancel = () => {
  Object.keys(ruleForm).forEach(key => {
    if (key == "strWeiHaiYinSuZhongLei") {
      ruleForm[key] = dataWeihu().variety;
    } else {
      ruleForm[key] = "";
    }
  });
  ruleForm.strSuoShuYuanQu = [];
  centerDialogVisible.value = false;
};

const addWiHaiYinSu = () => {
  ruleForm.strWeiHaiYinSuZhongLei = dataWeihu().variety;
  if (allHospitalinquiry.value.length != 0) {
    allHospitalinquiry.value.forEach((item: any) => {
      ruleForm.strSuoShuYuanQu.push(item);
    });
  }
  centerDialogVisible.value = true;
};

const strWeiHaiYinSuZhongLeiChange = () => {
  console.log(ruleForm.strSuoShuYuanQu);
};

const deleteWhys = async (params: any) => {
  console.log(params.row);
  // Tabledata.value = [params.row];
  ElMessageBox.confirm("确认删除吗？", "温馨提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    const data = {
      strWeiHaiYinSuId: params.row.WeiHaiYinSuID,
      iShunXu: params.row.ShunXu
    };
    DeleteWeiHaiYinSuDeleteport(data).then((res: any) => {
      console.log(res);
      if (res.Success == 0) {
        dataWeihu().WeiHaiYinSuChange();
        ElMessage({
          type: "success",
          message: "删除成功"
        });
      } else {
      }
    });
  });
};

watch(
  newShenQingDanOption,
  () => {
    Tabledata.value = newShenQingDanOption.value;
    console.log(Tabledata.value);
  },
  { deep: true }
);
// 控制分页显示隐藏
const showhidden = ref<boolean>(false);
const proTable = ref();
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<any>({
  strWeiHaiYinSuId: "",
  strWeiHaiYinSuMingCheng: "",
  strGuoBiaoDaiMa: "",
  strPym: "",
  strWeiHaiYinSuZhongLei: dataWeihu().variety,
  strSuoShuYuanQu: []
});
nextTick(() => {
  ruleForm.strWeiHaiYinSuZhongLei = dataWeihu().variety;
});

const rules = reactive<any>({
  strWeiHaiYinSuMingCheng: [
    {
      required: true,
      pattern: /^[^\s\d]+$/,
      message: "不能包含空格或数字",
      trigger: "blur"
    }
  ],
  strSuoShuYuanQu: [{ required: true, message: "不可为空", trigger: "blur" }],
  strGuoBiaoDaiMa: [
    {
      pattern: /^[0-9]+$/,
      message: "只能输入数字",
      trigger: "blur"
    }
  ]
});

const compile = (scope: any) => {
  console.log(scope.row, "1111111111111111");

  sole.value = scope.row.WeiHaiYinSuID;
  const dataArray = scope.row.SuoShuYuanQu.split(";").reduce((acc, item, index) => {
    acc[index] = item.trim();
    return acc;
  }, []);

  ruleForm.strWeiHaiYinSuId = scope.row.WeiHaiYinSuID;
  ruleForm.strWeiHaiYinSuMingCheng = scope.row.WeiHaiYinSuMingCheng;
  ruleForm.strGuoBiaoDaiMa = scope.row.GuoBiaoDaiMa;
  ruleForm.strPym = scope.row.PYM;
  ruleForm.strWeiHaiYinSuZhongLei = scope.row.WeiHaiYinSuZhongLei;
  ruleForm.strSuoShuYuanQu = dataArray;

  centerDialogVisible.value = true;
};

const WeiHaiYinSuConfirm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      if (ruleForm.strPym == "") {
        const firstChars = ruleForm.strWeiHaiYinSuMingCheng
          .split("")
          .map(char => pinyin(char, { style: pinyin.STYLE_NORMAL })[0])
          .join("")
          .replace(/[^a-zA-Z]/g, ""); // 使用正则表达式去除非字母字符

        const result = firstChars.toUpperCase(); // 转换为大写
        ruleForm.strPym = result;
      }
      if (ruleForm.strSuoShuYuanQu) {
        const result = ruleForm.strSuoShuYuanQu.join(";");
        ruleForm.strSuoShuYuanQu = result;
      }
      if (ruleForm.strWeiHaiYinSuId == "") {
        PostWeiHaiYinSuAddport(ruleForm).then((res: any) => {
          if (res.Success == 0) {
            Tabledata.value.push(res.Data);
            cancel();
            ElMessage.success("添加成功");
          } else {
            cancel();
          }
        });
      } else if (ruleForm.strWeiHaiYinSuId != "") {
        PutWeiHaiYinSuUpdateport(ruleForm).then((res: any) => {
          console.log(res);
          if (res.Success == 0) {
            console.log(ruleForm);
            Tabledata.value.forEach(item => {
              if (item.WeiHaiYinSuID === sole.value) {
                item.GuoBiaoDaiMa = res.Data.GuoBiaoDaiMa;
                item.PYM = res.Data.PYM;
                item.ShunXu = res.Data.ShunXu;
                item.SuoShuYuanQu = res.Data.SuoShuYuanQu;
                item.WeiHaiYinSuID = res.Data.WeiHaiYinSuID;
                item.WeiHaiYinSuMingCheng = res.Data.WeiHaiYinSuMingCheng;
                item.WeiHaiYinSuZhongLei = res.Data.WeiHaiYinSuZhongLei;
                item.tid = res.Data.tid;
              }
            });
            cancel();
            ElMessage.success("编辑成功");
          } else {
            cancel();
          }
        });
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

// 另存
const saveas = () => {
  console.log(1111);
  ElMessageBox.prompt("请输入危害因素名称", "危害因素另存为", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    inputPattern: /^[^\s]+$/,
    inputErrorMessage: "不可为空"
  }).then(({ value }) => {
    if (dataWeihu().sole == "" || dataWeihu().sole == undefined) {
      return ElMessage({
        type: "error",
        message: `请先选择危害因素`
      });
    }
    const data = {
      strWeiHaiYinSuId: dataWeihu().sole,
      strLingCunMingCheng: value
    };
    PostWeiHaiYinSuLingCunport(data).then((res: any) => {
      console.log(res);
      if (res.Success == 0) {
        Tabledata.value.push(res.Data);
        ElMessage({
          type: "success",
          message: `另存为成功`
        });
      }
    });
  });
};

// 取消
const WeiHaiYinSuCancel = () => {
  cancel();
};
const [jdstrWeiHaiYinSuMingCheng, onDrawerOpened] = useFocusInput();
const [strPymjd, strWeiHaiYinSuMingChengDown] = useFocusInput();
// 表格配置项
const columns = reactive<any>([
  {
    // 加上 sort 就获取不到当前行的数据
    type: "sort",
    label: "排序",
    width: 80
  },
  { type: "index", label: "序号", width: 80 },
  { prop: "WeiHaiYinSuMingCheng", label: "危害因素名称" },
  { prop: "operation", label: "操作", fixed: "right", width: 150 }
]);
// 调序
const dargSort = (item: any) => {
  console.log(item);
  const data = {
    strWeiHaiYinSuId: item.removedItem.WeiHaiYinSuID,
    strZhongLei: item.removedItem.WeiHaiYinSuZhongLei,
    iTiaoZhengQianShunXu: item.removedItem.ShunXu,
    iTiaoZhengHouShunXu: item.newIndex + 1
  };
  PutWeiHaiYinSunTiaoZhengShunXuport(data).then((res: any) => {
    console.log(res);
  });
};
</script>

<style scoped lang="scss">
.ApplicationForm {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  .ApplicationForm-search {
    height: 25px;
    padding: 10px 20px;
    background-color: white;
    border-radius: 5px;
    .ApplicationForm-search-span-ls {
      font-size: larger;
      font-weight: 900;
      line-height: 0;
      color: #239487;
    }
    .ApplicationForm-search-span {
      margin-left: 5px;
      color: #239487;
    }
  }
  .ApplicationFormTableOne {
    height: calc(100vh - 280px);
    margin-top: 5px;
  }
}
</style>
